package com.hqyj.controller;

import com.hqyj.pojo.Role;
import com.hqyj.pojo.User;
import com.hqyj.pojo.UserAndRole;
import com.hqyj.pojo.UserRole;
import com.hqyj.service.RoleService;
import com.hqyj.service.UserRoleService;
import com.hqyj.service.UserService;
import com.hqyj.util.MD5Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.net.URLEncoder;
import java.util.*;

import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * @author chen3
 * @description
 * @date 2021-08-12 9:57
 */
@Controller
@RequestMapping("user")
public class UserController {
    private static HashMap<String,HashMap<String,Object>> map=new HashMap<>();

    public static HashMap<String, HashMap<String, Object>> getMap() {
        return map;
    }

    @Autowired
    private UserService userService;

    @Autowired
    private UserRoleService userRoleService;

    @Autowired
    private RoleService roleService;

    @RequestMapping("/login")
    @ResponseBody
    public Map<String,Object> login(String username,String password){
        //检查请求参数
        if(username == null || password == null){
            Map<String, Object> result = new HashMap<>();
            result.put("code",-9);
            result.put("message","请求参数错误");
            return result;
        }
        //调用服务层实现业务
        return userService.login(username,password);
    }

    @RequestMapping("/logout")
    @ResponseBody
    public Map<String, Object> logout(){
        //调用服务层实现业务
        return userService.logout();
    }


    @RequestMapping("/register")
    public String register(User user, HttpServletRequest request, MultipartFile file) throws IOException {
        //注册只能注册用户
        user.setRoleId(3);
        if(file!=null&&file.getOriginalFilename()!="") {
            final String filename = file.getOriginalFilename();
            final String suffer = filename.substring(filename.lastIndexOf("."));
            final UUID uuid = UUID.randomUUID();
            final String path = request.getServletContext().getRealPath("static");
            final File upload = new File(path, "images");
            if (!upload.exists()) {
                upload.mkdirs();
            }
            String img = uuid + suffer;
            final File imgFile = new File(upload.getAbsolutePath(), img);
            file.transferTo(imgFile);
            user.setHeaderImg(img);
        }
        final Map<String, Object> map = userService.insetUser(user);
        if(map.get("message").equals("注册成功")){
            final UserRole userRole = new UserRole(user.getUsername(), user.getRoleId());
            userRoleService.insert(userRole);
        }
        request.setAttribute("data",map);
        return "register_result";
    }

    @RequestMapping("/IsExist")
    @ResponseBody
    public Map<String,Object> UsernameIsExist(String username){
        Map<String,Object> result = new HashMap<>();
        User user = userService.getOneByUsername(username);
        result.put("code",0);
        result.put("message","fail");
        if (user !=  null){
            result.put("code",1);
            result.put("message","success");
            result.put("data",user);
        }
        return result;
    }

    @RequestMapping("/userCenter")
    public String userCenter(HttpSession session){
        User loginUser = (User)session.getAttribute("loginUser");
        if (loginUser==null){
            return "unauthorized/unauthorized";
        }
        final User user = userService.getOneByUsername(loginUser.getUsername());
        session.setAttribute("loginUser",user);
        return "user/userCenter";
    }

    @RequestMapping("/admin")
    public String toadmin(){
        return "admin/admin";
    }

    @RequestMapping("/recharge")
    public void recharge(Double money, HttpServletRequest request,HttpServletResponse response,HttpSession session) throws ServletException, IOException {
        User loginUser = (User)session.getAttribute("loginUser");
        if(loginUser!=null){
            final HashMap<String, Object> hashMap = new HashMap<>();
            hashMap.put("recharge",money);
            hashMap.put("user",loginUser);
            String uuid = UUID.randomUUID().toString();
            map.put(uuid,hashMap);
            final String localhost = "192.168.2.174:8080/shop";
            //final String localhost = "192.168.2.174:8080"; //改为自己的地址
            String str=localhost+"/pay?token="+uuid;
            String url= URLEncoder.encode(str,"gbk");
            response.sendRedirect("https://api.pwmqr.com/qrcode/create/?url="+url);
        }
    }

    @RequestMapping("/mdfUserInfo")
    @ResponseBody
    public Map<String,Object> mdfUserInfo(User user){
        final HashMap<String, Object> map = new HashMap<>();
        if(user==null&&user.getUsername()==null){
            map.put("code",0);
            map.put("message","fail");
            return map;
        }else {
            //确保不能修改金额
            final User oneByUsername = userService.getOneByUsername(user.getUsername());
            user.setBalance(oneByUsername.getBalance());
            user.setRoleId(null);
            user.setPassword(null);
            user.setHeaderImg(null);
            int i=0;
            try {
                i = userService.updateUser(user);
            }catch (Exception e){
                map.put("code",-2);
                map.put("message","fail");
                return map;
            }

            if(i>=1){
                map.put("code",1);
                map.put("message","ok");
                return map;
            }else {
                map.put("code",-1);
                map.put("message","fail");
                return map;
            }
        }
    }



    @RequestMapping("/modifyRole")
    @ResponseBody
    public Map<String,Object> modifyRole(String username,Integer roleId){
        if(username != "" && roleId != null){
            return userService.modifyRole(username,roleId);
        }
        return null;
    }

    @RequestMapping("/checkPassword")
    @ResponseBody
    public Map<String,Object> checkPassword(String password,String username,HttpSession session){
        final HashMap<String, Object> hashMap = new HashMap<>();
        final User user = userService.getOneByUsername(username);
        final String s = MD5Util.md5Hash(password, username);
        if(s.equals(user.getPassword())){
            hashMap.put("code",1);
            hashMap.put("message","ok");
            session.setAttribute("change",true);
        }else {
            hashMap.put("code",0);
            hashMap.put("message","fail");
        }
        return hashMap;
    }

    @RequestMapping("/mdfPassword")
    @ResponseBody
    public Map<String,Object> mdfPassword(String password,HttpSession session){
        final HashMap<String, Object> hashMap = new HashMap<>();
        Object change = session.getAttribute("change");
        if(change!=null&&(boolean)change){
            session.setAttribute("change",false);
            final User user = new User();
            User loginUser = (User)session.getAttribute("loginUser");
            user.setUsername(loginUser.getUsername());
            user.setPassword(MD5Util.md5Hash(password,loginUser.getUsername()));
            user.setBalance(loginUser.getBalance());
            userService.updateUser(user);
            hashMap.put("code",1);
            hashMap.put("message","ok");
        }else {
            hashMap.put("code",0);
            hashMap.put("message","fail");
        }
        return hashMap;
    }

    @RequestMapping("/userlist")
    public ModelAndView userList(){
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("user/userList");
        List<UserAndRole> users = userService.queryAll();
        modelAndView.addObject("users",users);
        List<Role> roles = roleService.queryAllByLimit(0,500);
        modelAndView.addObject("roles",roles);
        return modelAndView;
    }

}
